"use client";

import { useState } from "react";
import Terminal from "./Terminal";

interface SharedPort {
    localPort: number;
    publicPort: number;
    url?: string;
    status?: 'active' | 'stopping' | 'error';
}

export default function TerminalExample() {
    const [sharedPorts, setSharedPorts] = useState<SharedPort[]>([]);

    const handleWebShare = async ({ localPort, publicPort }: { localPort: number; publicPort: number }) => {
        // Simulate WebShare API call with loading state
        const url = `http://localhost:${publicPort}`;
        const newPort: SharedPort = {
            localPort,
            publicPort,
            url,
            status: 'active'
        };

        setSharedPorts(prev => [...prev, newPort]);
        console.log(`✅ Sharing local port ${localPort} as public port ${publicPort}`);

        // Show success notification (you could integrate with a toast library here)
        alert(`Port ${localPort} is now accessible at ${url}`);
    };

    const handleWebUnshare = async ({ publicPort }: { publicPort: number }) => {
        // Simulate stopping process
        setSharedPorts(prev =>
            prev.map(port =>
                port.publicPort === publicPort
                    ? { ...port, status: 'stopping' as const }
                    : port
            )
        );

        // Simulate async stopping process
        setTimeout(() => {
            setSharedPorts(prev => prev.filter(port => port.publicPort !== publicPort));
            console.log(`🛑 Stopped sharing public port ${publicPort}`);
            alert(`Port ${publicPort} is no longer shared`);
        }, 1500);
    };

    return (
        <div className="p-4 bg-gray-900 min-h-screen">
            <div className="max-w-6xl mx-auto">
                <div className="mb-6">
                    <h1 className="text-3xl font-bold text-white mb-2">Terminal with WebShare</h1>
                    <p className="text-gray-400">
                        Click the Share button in the terminal header to expose local ports to the internet.
                        Stop sharing with the stop button next to each active port.
                    </p>
                </div>

                {/* Active Shared Ports Summary */}
                {sharedPorts.length > 0 && (
                    <div className="mb-6 p-4 bg-gray-800 rounded-lg border border-gray-700">
                        <h2 className="text-lg font-semibold text-white mb-3">Active Shared Ports</h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                            {sharedPorts.map((port, index) => (
                                <div key={index} className="bg-gray-700 rounded-md p-3 border border-gray-600">
                                    <div className="flex items-center justify-between mb-2">
                                        <span className="text-sm font-medium text-gray-300">
                                            Port {port.publicPort}
                                        </span>
                                        <div className={`w-2 h-2 rounded-full ${
                                            port.status === 'active' ? 'bg-green-500' :
                                            port.status === 'stopping' ? 'bg-yellow-500 animate-pulse' :
                                            'bg-red-500'
                                        }`} />
                                    </div>
                                    <div className="text-xs text-gray-400 mb-1">
                                        Local: {port.localPort}
                                    </div>
                                    {port.url && (
                                        <div className="text-xs text-blue-400 truncate">
                                            <a href={port.url} target="_blank" rel="noopener noreferrer" className="hover:underline">
                                                {port.url}
                                            </a>
                                        </div>
                                    )}
                                    {port.status === 'stopping' && (
                                        <div className="text-xs text-yellow-400 mt-1">
                                            Stopping share...
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <div className="space-y-4">
                        <h2 className="text-xl font-semibold text-white">Terminal 1 (Admin)</h2>
                        <p className="text-sm text-gray-400">Has write access to share ports</p>
                        <Terminal
                            id="terminal-1"
                            sessionId="session-1"
                            hasWriteAccess={true}
                            showChat={true}
                            onWebShare={handleWebShare}
                            onWebUnshare={handleWebUnshare}
                            sharedPorts={sharedPorts}
                            onChatMessage={(message) => {
                                console.log("Chat message:", message);
                            }}
                        />
                    </div>

                    <div className="space-y-4">
                        <h2 className="text-xl font-semibold text-white">Terminal 2 (Viewer)</h2>
                        <p className="text-sm text-gray-400">Read-only terminal</p>
                        <Terminal
                            id="terminal-2"
                            sessionId="session-2"
                            hasWriteAccess={false}
                            showChat={true}
                            sharedPorts={sharedPorts}
                            onChatMessage={(message) => {
                                console.log("Chat message:", message);
                            }}
                        />
                    </div>
                </div>

                {/* Instructions */}
                <div className="mt-8 p-4 bg-gray-800 rounded-lg border border-gray-700">
                    <h3 className="text-lg font-semibold text-white mb-3">How to Use WebShare</h3>
                    <ol className="space-y-2 text-sm text-gray-300">
                        <li>1. Click the "Share" button in the terminal header</li>
                        <li>2. Configure local and public ports</li>
                        <li>3. Click "Share Port" to expose the service</li>
                        <li>4. Access your service via the generated URL</li>
                        <li>5. Click the stop button (✕) to stop sharing</li>
                    </ol>
                </div>
            </div>
        </div>
    );
}